(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('apf.piUpload.uploadController', uploadController);
	uploadController.$inject = [ '$scope', '$q', 'Constants', 'gridService', 'modalService', 'layoutConfig', 'validatorConfig', 'authService',
			'piUploadService' ];
	function uploadController($scope, $q, Constants, gridService, modalService, layoutConfig, validatorConfig, authService, piUploadService) {
		var ctrl = this;
		var param = $scope.$stateParams.params;
		ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		ctrl.piLoad = {};

		
			
		ctrl.init = function() {
			authService.uploadInit(param).then(function(response) {
				ctrl.piLoad = response.data || param;
			});
		};

		ctrl.upload = function() {
			if (!ctrl.piLoad.fileList) {
				modalService.openErrorDialogs({
					'messages' : [ 'message.pi.fileisrequired']
				});
			} else {
				if ( ctrl.piLoad.fileList[0]) {
					var fileName = ctrl.piLoad.fileList[0].docFileName;
					
					ctrl.piLoad.srcFileName = fileName;

					ctrl.piLoad.docId = ctrl.piLoad.fileList[0].docId;
					
					if (fileName == null) {
						modalService.openErrorDialogs({
							'messages' : [ 'message.pi.fileisrequired']
						});
					} else {		
						var fmt = "";
						if (fileName.toLowerCase().endsWith(".apiv.fsdoc")) {
							fmt = "apiv.fsdoc";
						}else if(fileName.toLowerCase().endsWith(".xml")){
							fmt = "xml";
						}else if(fileName.toLowerCase().endsWith(".edi")){
							fmt = "edi";
						}
						if (fmt != "apiv.fsdoc" && fmt != "xml" && fmt != "edi") {
							modalService.openErrorDialogs({
								'messages' : [ 'message.pi.fileformat']
							});         
						} else {	
							ctrl.piLoad.dataFormat = fmt;
							return authService.upload(ctrl.piLoad).then(uploadSuccessful, uploadFailed);
						}
					}
				} else {
					modalService.openErrorDialogs({
						'messages' : [ 'message.pi.fileisrequired']
					});
				} 
			}
		};

		function uploadSuccessful(response) {
			delete ctrl.piLoad.fileList;//clear file list
			modalService.openAcknowledgeDialogs({
				'messages' : [ 'messages.pi.upload.success' ],
				'btnCallback' : {
					'close' : function() {
						$scope.go('apf.workflow.wfTxn.list');
					}
				},
				'redirections' : [ {
					'name' : 'title.infobar.workflow.list',
					'state' : 'apf.workflow.wfTxn.list',
					'params' : {}
				}]
			});
		}

		function uploadFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}

		
	}
})(angular);
